<template>
  <div>
    <span @click="onShowCheckCostModal">
      <slot></slot>
    </span>

    <el-dialog
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :draggable="true"
      v-model="checkCostModalVisible"
      class="check-dialog"
      width="70%"
      append-to-body
    >
      <template #header>
        <span> 审核费用</span>
      </template>
      <div class="top_no">
        <el-row>
          <el-col :span="6">费用单号：{{ feeNo }}</el-col>
          <el-col :span="6">
            审核状态：
            <el-tag type="warning">待审核</el-tag>
          </el-col>
          <el-col :span="6">工单单号：{{ workNo }}</el-col>
        </el-row>
      </div>
      <div class="table">
        <el-table :border="true" :data="tableDataList.feeDetails" resizable stripe>
          <!--序号-->
          <el-table-column fixed="left" label="序号" min-width="50" show-overflow-tooltip>
            <template v-slot="i">
              {{ i.$index + 1 }}
            </template>
          </el-table-column>

          <!--审核状态-->
          <el-table-column label="审核状态" show-overflow-tooltip width="120">
            <template #default="scope">
              <el-select v-model="scope.row.status" clearable filterable placeholder="审核状态">
                <el-option
                  v-for="item in options2"
                  :key="item.name"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <!--结算类型-->
          <el-table-column label="结算类型" show-overflow-tooltip width="150">
            <template #default="scope">
              <el-select v-model="scope.row.type" clearable filterable placeholder="结算类型">
                <el-option
                  v-for="item in settlementTypeOptional"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <!--费用项目-->
          <el-table-column label="费用项目" width="120">
            <template #default="scope">
              <el-select
                v-model="scope.row.workFeeProjectId"
                :loading="loading"
                :filter-method="getworkFeeProjectPageSelect"
                clearable
                filterable
                placeholder="请选择"
                remote-show-suffix
              >
                <el-option
                  v-for="item in modules"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                  @click="changeworkFeeProjectId(item, scope.$index)"
                />
              </el-select>
            </template>
          </el-table-column>

          <!--申请数量-->
          <el-table-column label="申请数量" show-overflow-tooltip width="90">
            <template #default="scope">
              <el-input
                v-model="scope.row.qty"
                clearable
                placeholder="数量"
                @input="scope.row.qty = scope.row.qty.replace(/\D/g, '')"
              />
            </template>
          </el-table-column>

          <!--单价金额-->
          <el-table-column label="单价金额" show-overflow-tooltip width="130">
            <template #default="scope">
              <el-input
                v-model="scope.row.price"
                clearable
                @input="scope.row.price = scope.row.price.replace(/[^\d.]/g, '')"
                @keyup="handlePriceKeyup($event, scope.$index)"
              >
                <template #prepend>￥</template>
              </el-input>
            </template>
          </el-table-column>

          <!--总金额-->
          <el-table-column label="总金额" show-overflow-tooltip width="100">
            <template #default="scope">
              <el-input
                :disabled="true"
                :value="scope.row.price * scope.row.qty"
                clearable
                @input="scope.row.price = scope.row.price.replace(/\D/g, '')"
              >
                <template #prepend>￥</template>
              </el-input>
            </template>
          </el-table-column>

          <!--备注-->
          <el-table-column label="备注" max-width="150" min-width="140" show-overflow-tooltip>
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="填写备注" />
            </template>
          </el-table-column>

          <!--附件-->
          <el-table-column :width="480" label="附件(最多上传8个)">
            <template #default="scope">
              <div class="updata_pic">
                <el-upload
                  :auto-upload="false"
                  :on-change="
                    (file) => {
                      getProImages(file, scope.$index)
                    }
                  "
                  :show-file-list="false"
                  accept="image/*,.pdf"
                  action="#"
                  list-type="picture-card"
                  multiple
                >
                  <div class="plus_add">
                    <el-icon size="12">
                      <Plus />
                    </el-icon>
                  </div>
                </el-upload>
                <div v-for="(img, index) in scope.row.images" :key="index" class="disf_ipc">
                  <img
                    v-if="img.image.replace(/.+\./, '') == 'pdf' || img.file?.type.includes('pdf')"
                    :src="pdf"
                    alt=""
                    style="width: 100%; cursor: pointer"
                  />
                  <img v-else :src="img.image" class="img" />
                  <span class="item-actions">
                    <el-icon
                      class="item-preview"
                      color="#fff"
                      size="12"
                      @click="handlePictureCardPreview(img.image)"
                      ><ZoomIn
                    /></el-icon>
                    <el-icon
                      class="item-delete"
                      color="#fff"
                      size="12"
                      @click="handleRemove(index, scope.$index)"
                      ><Delete
                    /></el-icon>
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer_remark">
        <!--审核备注-->
        <el-form-item label="审核备注">
          <el-input
            v-model="tableDataList.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            class="w_input"
            clearable
            maxlength="200"
            placeholder="填写备注信息"
            show-word-limit
            size="small"
            type="textarea"
          />
        </el-form-item>
      </div>

      <!--按钮组-->
      <div class="btns flex-justify-end" style="margin-top: 12px">
        <el-button
          :disabled="$route.query.isArchive == 'true'"
          class="btn_save"
          color="#007cff"
          @click="onSave"
          style="width: 80px"
          >确认审核
        </el-button>
        <el-button style="width: 60px" @click="checkCostModalVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="dialogVisible" draggable title="查看附件" top="8vh">
      <iframe
        :src="`${dialogImageUrl}`"
        frameborder="0"
        style="height: 660px; width: 100%"
      ></iframe>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, toRefs, watch } from 'vue'
  import { checkOrderFee, OrderFeeDetailProjectInfo, workFeeProjectPageSelect } from '@/api/order'
  import { orderAnnexUpload } from '@/api/upload'
  import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
  import pdf from '@/assets/image/pdf.png'
  import { ElMessage } from 'element-plus'
  import { checkNum } from '@/utils/validate'
  import _ from 'lodash'

  // 费用审核弹窗显示状态
  const checkCostModalVisible = ref(false)

  /**
   * 显示费用审核弹窗事件
   */
  const onShowCheckCostModal = () => {
    getworkFeeProjectPageSelect('')
    checkCostModalVisible.value = true
  }

  const props = defineProps({
    feeId: String,
    workNo: String,
    feeNo: String,
  })
  const { feeNo, workNo } = toRefs(props)
  const dialogVisible = ref(false)
  const dialogImageUrl = ref(null)
  const modules = ref(null)
  const loading = ref(false)
  const emits = defineEmits(['update-list'])

  // 结算类型
  const settlementTypeOptional = [
    { name: '向服务商支付', value: 1 },
    { name: '商家收取', value: 2 },
    { name: '平台承担', value: 3 },
  ]

  // 审核状态
  const options2 = [
    { name: '已通过', value: 2 },
    { name: '已驳回', value: 3 },
  ]
  const tableDataList = reactive({
    feeDetails: [
      {
        delImageIds: [], // 删除的工单费用图片对象ID
        id: null, // 费用项目详情ID，新增不必传，修改必传
        images: [
          {
            id: null,
            image: '',
            file: null,
          },
        ],
        price: '', // 费用金额
        qty: 1, // 数量
        remark: '', // 备注
        status: 1, // 审核状态 1-待审核，2-已通过，3-已驳回
        type: 1, // 结算类型：1-向服务商收取，2-向服务商支付，3-向客户收取，4-向客户支付,示例值(1)
        workFeeProjectId: null, // 工单费用项目ID
        updatePrice: false,
      },
    ],
    id: null, //服务费用项目ID
    remark: '', //	审核备注
  })

  // 费用项目下拉数据
  const getworkFeeProjectPageSelect = _.throttle((query: string) => {
    loading.value = true
    let data = {
      limit: 0,
      name: query,
      page: 0,
    }
    workFeeProjectPageSelect(data).then((res) => {
      if (res.data.success) {
        modules.value = res.data.data.rows
      } else {
        if(res.data.isError) ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 4000,
          type: 'error',
        })
      }
      loading.value = false
    })
  }, 500)

  // 保存
  async function onSave() {
    for (const key in tableDataList.feeDetails) {
      let imgobj = tableDataList.feeDetails[key]
      if (imgobj.images.length > 0) {
        let arrimg = []
        for (let i = 0; i < imgobj.images.length; i++) {
          if (imgobj.images[i].file) {
            arrimg = [imgobj.images[i].file]
            imgobj.images.splice(i, 1)
            const res = await orderAnnexUpload(arrimg)
            imgobj.images.push(...res.data.data.rows.map((o) => ({ id: null, image: o })))
          }
        }
      }
    }
    const res = await checkOrderFee(tableDataList)
    if (res.data.success) {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'success',
        duration: 3000,
      })
      emits('update-list')
      checkCostModalVisible.value = false
    } else {
      if(res.data.isError) ElMessage({
        showClose: true,
        message: res.data.message,
        duration: 4000,
        type: 'error',
      })
    }
  }

  // 费用项目选择变化
  function changeworkFeeProjectId(item, index) {
    tableDataList.feeDetails[index].price = item.price
    tableDataList.feeDetails[index].updatePrice = item.updatePrice
  }

  // 获取详情
  const getOrderFeeDetailProjectInfo = async (id) => {
    await OrderFeeDetailProjectInfo(id).then((res) => {
      if (res.data.success) {
        tableDataList.feeDetails = res.data.data.row.map((o) => {
          o.status = o.status == 1 ? 2 : o.status
          return { ...o, statusType: o.status, delImageIds: [] }
        })
      } else {
        if(res.data.isError) ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 4000,
          type: 'error',
        })
      }
    })
  }
  // 查看图片
  const handlePictureCardPreview = (img) => {
    dialogImageUrl.value = img
    dialogVisible.value = true
  }
  watch(dialogVisible,(n)=>{
    if(!n){
      dialogImageUrl.value ='about:blank'
    }
  })
  // 添加图片
  const getProImages = (img, index) => {
    if (tableDataList.feeDetails[index].images.length >= 8) {
      ElMessage({
        showClose: true,
        message: '最多上传8个',
        duration: 4000,
        type: 'error',
      })
      return
    }
    tableDataList.feeDetails[index].images.push({ image: img.url, file: img.raw, id: null })
  }
  // 删除图片
  const handleRemove = (imgindex, index) => {
    tableDataList.feeDetails[index].images = tableDataList.feeDetails[index].images.filter(
      (o, i) => {
        if (i == imgindex && o.id) {
          tableDataList.feeDetails[index].delImageIds.push(o.id)
        }
        return i != imgindex
      },
    )
  }
  // 单价键盘按下事件
  const handlePriceKeyup = (event: Event, index: number) => {
    checkNum(event)
    tableDataList.feeDetails[index].price = (event.target as HTMLInputElement).value
  }

  watch(
    () => props.feeId,
    async (value) => {
      if (value) {
        tableDataList.id = value
        await getOrderFeeDetailProjectInfo(value)
      }
    },
  )
</script>
<style lang="scss" scoped>
  :deep(.el-select__wrapper) {
    min-height: 28px !important;
    border-radius: 2px !important;
    font-size: 12px !important;
  }

  :deep(.el-input__wrapper) {
    height: 28px !important;
    font-size: 12px !important;
  }

  .top_no {
    padding-bottom: 8px;
    font-size: 12px;
    color: #999;
  }

  .operation {
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      cursor: pointer;
      margin: 0 6px;

      &:hover {
        transform: scale(1.2);
      }
    }
  }

  :deep(.el-table td.el-table__cell) {
    .el-input {
      .el-input__wrapper {
        height: 28px;
      }

      .el-input-group__prepend {
        padding: 0 2px;
      }
    }
  }

  .footer_remark {
    margin-top: 20px;

    .w_input {
      width: 600px;
      margin-left: 10px;
    }
  }

  :deep(.el-upload-list--picture-card) {
    display: flex;
    flex-wrap: nowrap;
    justify-content: flex-end;
    align-items: center;
    flex-direction: row-reverse;

    .el-upload {
      width: 40px;
      height: 40px;
      margin: 0 8px 0 0;
    }

    .el-upload-list__item {
      width: 40px;
      height: 40px;
      margin: 0 8px 0 0;
    }
  }

  :deep(.updata_pic) {
    display: flex;
    align-items: center;

    .el-upload {
      &.el-upload--picture-card {
        width: 40px;
        height: 40px;
      }
    }

    .disf_ipc {
      display: flex;
      width: 40px;
      height: 40px;
      position: relative;
      margin-left: 6px;
      border: 1px solid #7f7f7f27;
      border-radius: 4px;
      box-sizing: border-box;
      overflow: hidden;

      .img {
        width: 100%;
        position: absolute;
        border-radius: 4px;
      }

      .item-actions {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        opacity: 0;
      }

      &:hover .item-actions {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #7f7f7f9d;
        opacity: 1;
        border-radius: 4px;

        .item-preview {
          margin: 0 4px;
          cursor: pointer;

          &:hover {
            transform: scale(1.2);
          }
        }

        .item-delete {
          margin: 0 4px;
          cursor: pointer;

          &:hover {
            transform: scale(1.2);
          }
        }
      }
    }
  }

  @import '../index.scss';
</style>
